import { tap, switchMap } from 'rxjs/operators'
import { Observable } from 'rxjs'
import * as ejs from 'ejs'
import { bootstrap } from './core'
import { join } from 'path'
import { fileExist } from '../../functions/index'
export interface MainOptions {
  base: string
  port: number
  host: string
  app: any
  install: any
}
import { createHtmlEngine as installCreateHtmlEngine } from '../../../public/install'
import { createHtmlEngine as mobileCreateHtmlEngine } from '../../../public/mobile'
import { createHtmlEngine as webCreateHtmlEngine } from '../../../public/web'

export function main(option: MainOptions): Observable<any> {
  return fileExist(join(__dirname, 'data', 'install.loc')).pipe(
    switchMap(exist => {
      if (exist) {
        return bootstrap(
          option.port,
          option.host,
          option.app,
          webCreateHtmlEngine(),
          {
            cors: true
          },
          tap(app => app.enableCors())
        )
      } else {
        return bootstrap(
          option.port,
          option.host,
          option.install,
          installCreateHtmlEngine(),
          {
            cors: true
          },
          tap(app => app.enableCors())
          // tap(app => {
          //   app.useStaticAssets(option.base + '/public/install/browser')
          //   app.setBaseViewsDir(option.base + '/public/install/browser')
          //   app.setViewEngine('hbs')
          // })
        )
      }
    })
  )
}
